package com.shanghaionstar.service;

import android.content.Context;
import android.util.SparseArray;

import com.google.gson.Gson;
import com.onstar.cn.api.UsersService;
import com.onstar.cn.api.VehicleService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.CommonError;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.sqlite.entities.PollingEntity;

import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.VehicleCommand;
import com.onstar.cn.vehicle.entity.VehicleDiagnosticItem;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.CarManageActivity;
import com.shanghaionstar.home.model.DrivingScore;
import com.shanghaionstar.mro.MrOActivity;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by 6335yz on 2016/7/5.
 */
public class DataRefreshService extends BaseService {

    private LogManager log = LogManager.getInstance();
    private Context context;
    private VehicleManager manager;

    public DataRefreshService(Context context) {
        this.context = context;
        manager = new VehicleManager(context, Constants.CURRENT_SERVER_URL);
    }

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public Object jsonToBean(String json) {
       // return new HomeModel();
        return null;
    }

    public Observable<String> doDataRefresh() {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(dataRefresh());
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    /**
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     * @Title: diagnostics
     * @Description: diagnostics service
     */
    private String diagnostics() {
        VehicleCommand vecicleCommand = new VehicleCommand();
        VehicleDiagnosticItem diagnosticItem = new VehicleDiagnosticItem();
        diagnosticItem.setDiagnosticItem(ApplicationUtil.getInstance().getSupportedDiagnostic());
        String[] supportDig = ApplicationUtil.getInstance().getSupportedDiagnostic();
        log.d("supportDig--------------------->>>" + Arrays.toString(supportDig));
        vecicleCommand.setDiagnosticsRequest(diagnosticItem);
        return GsonHelper.toJson(vecicleCommand);
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
    public String dataRefresh() throws OnStarException {

        //记录是否由小O做的车况刷新操作
        if (context instanceof MrOActivity || (context instanceof CarManageActivity && CarManageActivity.MRO.equalsIgnoreCase(((CarManageActivity)context).from))){
            PreferencesUtls.getInstance(context).putBoolean(FinalConstants.SharedPreferencesConfig.IF_REFRESH_DATA_FROM_MRO,true);
        }else {
            PreferencesUtls.getInstance(context).putBoolean(FinalConstants.SharedPreferencesConfig.IF_REFRESH_DATA_FROM_MRO,false);
        }

        VehicleService service = new VehicleService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        String body = diagnostics();
        service.commands(requestEntity, RemoteCommandsType.COMMANDS_DIAGNOSTICS, ApplicationUtil.getInstance().getVin(),body);
        BusinessUtil.initPollingStatusBeforePolling(RemoteCommandsType.COMMANDS_DIAGNOSTICS, ApplicationUtil.getInstance().getVin(),manager);

        requestEntity = HttpInjectUtils.injectHttp(getClass(), "dataRefresh", requestEntity);
        SparseArray<String> reseponseData = getDatas(requestEntity);
        if (reseponseData != null && reseponseData.size()!=0) {
            int responseCode = -1;
//            for (Integer key : reseponseData.keySet()) {
//                responseCode = key;
//                break;
//            }
            for(int i=0;i<reseponseData.size();i++) {
                responseCode = reseponseData.keyAt(i);
                break;
            }
            if (responseCode != 200 && responseCode != 202) {
                CommonError commonError = GsonHelper.fromJson(reseponseData.get(responseCode),CommonError.class);
                HttpException httpException = new HttpException(commonError.getErrorCode(), commonError.getErrorMessage());
                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, httpException);
                BusinessUtil.updateToFailPollingStatusBeforePolling(RemoteCommandsType.COMMANDS_DIAGNOSTICS, ApplicationUtil.getInstance().getCurrentVehicle().getVin(),manager);
                throw new HttpException(errorInfo.getCode(), errorInfo.getMsg());
            } else {
                //成功请求
                String json = reseponseData.get(responseCode);
                log.d("dataRefresh--->"+json);
                JSONObject error = GsonHelper.getJsonObject(json, "error");
                JSONObject commandResponse = GsonHelper.getJsonObject(json, "commandResponse");
                if (error != null) {
                    processError();
                } else if (commandResponse != null) {
                    String url;
                    try {
                        url = commandResponse.getString("url");
                        String requestId = url.substring(url.lastIndexOf("s") + 2, url.length());
                        // 拿到Request ID执行轮训刷新数据,
                        // 目前为Mock数据阶段，需先到遥控页拿一次token，这样才能执行本请求
                        PollingEntity entity = new PollingEntity();
                        entity.setVin(ApplicationUtil.getInstance().getVin());
                        entity.setToken(ApplicationUtil.getInstance().getToken());
                        entity.setRequestType(RemoteCommandsType.COMMANDS_DIAGNOSTICS.value());
                        entity.setRequestId(requestId);
                        manager.startPoll(entity);
                    } catch (JSONException e) {
                        processError();
                    }
                }
                return json;
            }
        }
        return null;
    }

    private void processError() throws OnStarException {
        BusinessUtil.updateToFailPollingStatusBeforePolling(RemoteCommandsType.COMMANDS_DIAGNOSTICS, ApplicationUtil.getInstance().getVin(),
                manager);
        throw new OnStarException("", context.getString(R.string.get_condition_error));
    }

    public Observable<DrivingScore> loadDrivingScore() {
        return Observable.defer(new Func0<Observable<DrivingScore>>() {
            @Override
            public Observable<DrivingScore> call() {
                try {
                    return Observable.just(doLoadDrivingScore());
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public DrivingScore doLoadDrivingScore() throws OnStarException {
        String idpId = ApplicationUtil.getInstance().getIdpID();
        String vin = null;
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getVin())) {
            vin = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        }
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        service.getDrivingScore(requestEntity, idpId, vin,ApplicationUtil.getInstance().getAccountId());
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "doLoadDrivingScore", requestEntity);
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        DrivingScore drivingScore = new Gson().fromJson(response,DrivingScore.class);
        return drivingScore;
    }

}
